package recite.word.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import recite.word.client.service.IBookService;
import recite.word.client.service.IIndexService;
import recite.word.client.service.IUserService;
import recite.word.client.service.IUserWordService;
import recite.word.client.vo.index.IndexGetDataVO;
import recite.word.mybatis.auto.model.Book;
import recite.word.mybatis.auto.model.User;
import recite.word.mybatis.auto.model.UserWord;
import recite.word.service.base.common.enums.DeleteEnum;
import recite.word.service.base.common.threadLocal.UserContent;
import recite.word.service.base.util.date.DateFormat;

import java.util.Calendar;
import java.util.Date;

@Service
public class IndexServiceImpl implements IIndexService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IBookService bookService;
    @Autowired
    private IUserWordService userWordService;
    /**
     * 获取首页数据
     * @return
     */
    @Override
    public IndexGetDataVO getData() {
        Long userId = UserContent.get();
        User user = userService.getById(userId);
        Long bookId = user.getPlanBookId();
        Book book = bookService.getById(bookId);
        LambdaQueryWrapper<UserWord> wrapper = new LambdaQueryWrapper<UserWord>()
                .eq(UserWord::getUserId, userId)
                .eq(UserWord::getBookId, bookId)
                .eq(UserWord::getIsRecite,true)
                .eq(UserWord::getDeleteStatus, DeleteEnum.NOT_DELETED.getCode());
        int totalHaveStudyNum = userWordService.count(wrapper);
        int remainDay = (int)Math.ceil((double)(book.getVocabulary() - totalHaveStudyNum) / user.getEverydayWordNum());
        String nowDate = DateFormat.format(new Date());
        LambdaQueryWrapper<UserWord> wrapper2 = wrapper.clone();
        wrapper.eq(UserWord::getReciteDate,nowDate);
        int dayHaveStudyNum = userWordService.count(wrapper);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,-1);
        String yesterdayDate = DateFormat.format(instance.getTime());
        wrapper2.eq(UserWord::getReciteDate,yesterdayDate);
        int reviewNum = userWordService.count(wrapper2);
        return IndexGetDataVO.builder()
                .bookId(bookId)
                .dayWord(user.getEverydayWordNum())
                .remainDay(remainDay)
                .studyBook(book.getName())
                .bookDesc(book.getDesc())
                .totalHaveStudyNum(totalHaveStudyNum)
                .totalNum(book.getVocabulary())
                .dayHaveStudyNum(dayHaveStudyNum)
                .reviewNum(reviewNum)
                .build();
    }
}
